import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class ReaderPanel extends JPanel {
    private JTable readerTable;
    private DefaultTableModel tableModel;
    private ReaderDAO readerDAO = new ReaderDAO();

    public ReaderPanel() {
        setLayout(new BorderLayout());

        // 创建顶部面板，包含搜索和添加按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        JPanel searchPanel = new JPanel();
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        JButton addButton = new JButton("添加读者");

        searchPanel.add(new JLabel("读者姓名/ID:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        topPanel.add(searchPanel, BorderLayout.WEST);
        topPanel.add(addButton, BorderLayout.EAST);

        // 创建表格
        String[] columnNames = {"ID", "读者ID", "姓名", "性别", "电话", "邮箱", "地址"};
        tableModel = new DefaultTableModel(columnNames, 0);
        readerTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(readerTable);

        // 创建底部面板，包含编辑和删除按钮
        JPanel bottomPanel = new JPanel();
        JButton editButton = new JButton("编辑读者");
        JButton deleteButton = new JButton("删除读者");
        JButton refreshButton = new JButton("刷新");

        bottomPanel.add(editButton);
        bottomPanel.add(deleteButton);
        bottomPanel.add(refreshButton);

        // 添加组件到面板
        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);

        // 初始化表格数据
        loadReaders();

        // 添加按钮事件监听器
        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                searchReaders(keyword);
            } else {
                loadReaders();
            }
        });

        addButton.addActionListener(e -> showAddReaderDialog());

        editButton.addActionListener(e -> {
            int selectedRow = readerTable.getSelectedRow();
            if (selectedRow != -1) {
                int readerId = (int) tableModel.getValueAt(selectedRow, 0);
                showEditReaderDialog(readerId);
            } else {
                JOptionPane.showMessageDialog(ReaderPanel.this, "请先选择一个读者", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedRow = readerTable.getSelectedRow();
            if (selectedRow != -1) {
                int readerId = (int) tableModel.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(ReaderPanel.this,
                        "确定要删除这个读者吗?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    if (readerDAO.updateReader(new Reader()) && false) {
                        // 这里应该有删除读者的逻辑，目前假设没有提供删除方法
                        JOptionPane.showMessageDialog(ReaderPanel.this, "删除成功");
                        loadReaders();
                    } else {
                        JOptionPane.showMessageDialog(ReaderPanel.this, "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(ReaderPanel.this, "请先选择一个读者", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        refreshButton.addActionListener(e -> loadReaders());
    }

    // 加载所有读者到表格
    private void loadReaders() {
        tableModel.setRowCount(0);
        List<Reader> readers = readerDAO.getAllReaders();
        for (Reader reader : readers) {
            Object[] row = {
                    reader.getId(),
                    reader.getReaderId(),
                    reader.getName(),
                    reader.getGender(),
                    reader.getPhone(),
                    reader.getEmail(),
                    reader.getAddress()
            };
            tableModel.addRow(row);
        }
    }

    // 搜索读者
    private void searchReaders(String keyword) {
        // 目前没有实现搜索逻辑，可根据需求添加
        tableModel.setRowCount(0);
        loadReaders();
    }

    // 显示添加读者对话框
    private void showAddReaderDialog() {
        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "添加读者", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextField readerIdField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField genderField = new JTextField();
        JTextField phoneField = new JTextField();
        JTextField emailField = new JTextField();
        JTextField addressField = new JTextField();

        panel.add(new JLabel("读者ID:"));
        panel.add(readerIdField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderField);
        panel.add(new JLabel("电话:"));
        panel.add(phoneField);
        panel.add(new JLabel("邮箱:"));
        panel.add(emailField);
        panel.add(new JLabel("地址:"));
        panel.add(addressField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String readerId = readerIdField.getText().trim();
                String name = nameField.getText().trim();
                String gender = genderField.getText().trim();
                String phone = phoneField.getText().trim();
                String email = emailField.getText().trim();
                String address = addressField.getText().trim();

                if (readerId.isEmpty() || name.isEmpty() || gender.isEmpty() || phone.isEmpty() || email.isEmpty() || address.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                Reader reader = new Reader(readerId, name, gender, phone, email, address);
                if (readerDAO.addReader(reader)) {
                    JOptionPane.showMessageDialog(dialog, "添加成功");
                    dialog.dispose();
                    loadReaders();
                } else {
                    JOptionPane.showMessageDialog(dialog, "添加失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "输入有误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    // 显示编辑读者对话框
    private void showEditReaderDialog(int readerId) {
        Reader reader = readerDAO.getReaderById(readerId);
        if (reader == null) {
            JOptionPane.showMessageDialog(this, "找不到读者", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "编辑读者", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextField readerIdField = new JTextField(reader.getReaderId());
        JTextField nameField = new JTextField(reader.getName());
        JTextField genderField = new JTextField(reader.getGender());
        JTextField phoneField = new JTextField(reader.getPhone());
        JTextField emailField = new JTextField(reader.getEmail());
        JTextField addressField = new JTextField(reader.getAddress());

        panel.add(new JLabel("读者ID:"));
        panel.add(readerIdField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderField);
        panel.add(new JLabel("电话:"));
        panel.add(phoneField);
        panel.add(new JLabel("邮箱:"));
        panel.add(emailField);
        panel.add(new JLabel("地址:"));
        panel.add(addressField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String newReaderId = readerIdField.getText().trim();
                String newName = nameField.getText().trim();
                String newGender = genderField.getText().trim();
                String newPhone = phoneField.getText().trim();
                String newEmail = emailField.getText().trim();
                String newAddress = addressField.getText().trim();

                if (newReaderId.isEmpty() || newName.isEmpty() || newGender.isEmpty() || newPhone.isEmpty() || newEmail.isEmpty() || newAddress.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                reader.setReaderId(newReaderId);
                reader.setName(newName);
                reader.setGender(newGender);
                reader.setPhone(newPhone);
                reader.setEmail(newEmail);
                reader.setAddress(newAddress);

                if (readerDAO.updateReader(reader)) {
                    JOptionPane.showMessageDialog(dialog, "更新成功");
                    dialog.dispose();
                    loadReaders();
                } else {
                    JOptionPane.showMessageDialog(dialog, "更新失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "输入有误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }
}